package li.com.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import li.com.ruiji.common.R;
import li.com.ruiji.dto.DishDto;
import li.com.ruiji.entity.Category;
import li.com.ruiji.entity.Dish;
import li.com.ruiji.entity.DishFlavor;
import li.com.ruiji.service.CategoryService;
import li.com.ruiji.service.DishFlavorService;
import li.com.ruiji.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
@Api("菜品相关操作")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

//    添加菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //        指定删除修改后的菜品信息
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);

//        全部删除菜品信息
//        Set<String> keys1 = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys1);
        return R.success("添加菜品成功");
    }
//    显示菜品信息
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
//        分页构造器
         Page<Dish> pageInfo=new Page<>(page,pageSize);
         Page<DishDto> dishDtoPage =new Page<>();

//         条件构造器
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo,queryWrapper);
//        拷贝对象，（原，副，过滤属性）
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();  //新建一个实体类
            BeanUtils.copyProperties(item, dishDto);  //拷贝原有信息
            Long categoryId = item.getCategoryId();   // 获取分类的id
            Category categoryById = categoryService.getById(categoryId); //通过分类的id查询
            if(categoryById!=null){  //判断是否有该分类
                String categoryName = categoryById.getName();  //获取得到的分类id的名称
                dishDto.setCategoryName(categoryName);   //新建的实体类中的'分类'属性注入分类名称
            }
            return dishDto;     // 返回实体类
        }).collect(Collectors.toList());//将records列表每个元素打开进行操作再进行组合

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);

    }

//    修改菜品,页面回显
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }
//    修改菜品,完成修改操作
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
//        指定删除修改后的菜品信息
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);

//        全部删除菜品信息
//        Set<String> keys1 = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys1);
        return R.success("菜品修改成功");
    }
//    菜品停用
    @PostMapping("/status/0")
    public R<String> status0(Long[] ids){
        log.info(""+ids);
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(0);
            dishService.updateById(dish);
            String key="dish_"+dish.getCategoryId()+"_1";
            redisTemplate.delete(key);
        }

        return R.success("菜品修改成功");
    }
//    菜品启用
    @PostMapping("/status/1")
    public R<String> status1(Long[] ids){
        log.info(""+ids);
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(1);
            dishService.updateById(dish);
            //        指定删除修改后的菜品信息
            String key="dish_"+dish.getCategoryId()+"_1";
            redisTemplate.delete(key);

    //        全部删除菜品信息
    //        Set<String> keys1 = redisTemplate.keys("dish_*");
    //        redisTemplate.delete(keys1);
        }
        return R.success("菜品修改成功");
    }

//    菜品(批量)删除
    @DeleteMapping
    public R<String> delete(Long[] ids){
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            String key="dish_"+dish.getCategoryId()+"_1";
            redisTemplate.delete(key);
            dishService.removeById(id);
        }
        return R.success("批量删除成功");
    }

//    添加套餐时菜品选择内容(包括客户端购买菜品时显示的内容)
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> listDto=new ArrayList<>();
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
//        先从redis中查找该菜品有没有存入缓存
//        如果有，直接返回
        listDto= (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(listDto!=null){
            return R.success(listDto);
        }
//        如果没有，按照之前方法查找数据库
//        条件构造器
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        listDto= list.stream().map((item->{
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                dishDto.setCategoryName(category.getName());
            }
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(list1);
            return dishDto;
        })).collect(Collectors.toList());
//        查找到之后存入缓存
        redisTemplate.opsForValue().set(key,listDto,60, TimeUnit.MINUTES);
        return R.success(listDto);

    }
}
